|
|
|
|
|
|
|
Creating a Simple Error Handler |
|
|
|
|
|
|
|
|
To start, let's write a simple error-handling routine to illustrate how Visual Basic behaves when errors occur. Start up a new Standard EXE project in Visual Basic 5. Add a single command button to the default form. Set its Name property to cmdSimpleErr and its Caption Property to Simple. Now add the code in Listing 14.2 to support the command button. |
|
|
|
|
|
|
|
|
Listing 14.2. Writing a simple error handler. |
|
|
|
|
|
|
|
|
Private Sub cmdSimpleErr_Click()
'
' a simple error handler
'
On Error GoTo LocalErr ' turn on error handling
'
Dim intValue As Integer ' declare integer
Dim strMsg As String ' declare string
intValue = 10000000 ' create overflow error
GoTo LocalExit ' exit if no error
'
' local error handler
LocalErr:
strMsg = CStr(Err.Number) & " - " & Err.Description ' make message
MsgBox strMsg, vbCritical, "cmdSimpleErr_Click" ' show message
Resume Next ' continue on
'
' routine exit
LocalExit:
'
End Sub |
|
|
|
|
|
|
|
|
Save the form as BASICERR.FRM, and save the project as BASICERR.VBP. Then execute the program and click the command button. You see the error message displayed on the screen (see Figure 14.1). |
|
|
|
|
|
|
|
|
The example in Listing 14.2 exhibits all the parts of a good error handler. The first line in the routine tells Visual Basic what to do in case of an error. Notice that the name for the error-handling code is given as LocalErr. (Every local error handler written in this book is called LocalErr.) Next, the routine declares an integer variable and then purposely loads that variable with an illegal value. This causes the error routine to kick in. |
|
|
|
|
|
|
|
|
The error routine is very simple. It is a message that contains the error number and the associated text message. The routine then displays that message along with the warning symbol and the name of the routine that is reporting the error. |
|
|
|
|
|